package com.scs.application.core.excel.handler;

import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * @Description: 用户导入聚合数据处理器
 */
public class AggregationDataHandler extends ExcelDataHandlerDefaultImpl {

    private List<IExcelDataHandler> handlers = Lists.newArrayList();

    public AggregationDataHandler(List<IExcelDataHandler> handlers) {

        this.handlers = handlers;
    }

    public AggregationDataHandler(IExcelDataHandler... handlers) {
        this(handlers == null ? Lists.newArrayList() : Lists.newArrayList(handlers));
    }

    @Override
    public String[] getNeedHandlerFields() {
        List<String> fields = Lists.newArrayList();
        for (IExcelDataHandler handler : handlers) {
            String[] needHandlerFields = handler.getNeedHandlerFields();
            if (needHandlerFields == null) {
                continue;
            }
            for (String needHandlerField : needHandlerFields) {
                fields.add(needHandlerField);
            }
        }
        return fields.toArray(new String[fields.size()]);
    }

    @Override
    public Object importHandler(Object obj, String name, Object value) {
        for (IExcelDataHandler handler : handlers) {
            String[] needHandlerFields = handler.getNeedHandlerFields();
            List<String> fieldList = Lists.newArrayList(needHandlerFields);
            if (fieldList.contains(name)) {
                handler.importHandler(obj, name, value);
                break;
            }
        }
        return super.importHandler(obj, name, value);
    }

    @Override
    public Object exportHandler(Object obj, String name, Object value) {
        for (IExcelDataHandler handler : handlers) {
            String[] needHandlerFields = handler.getNeedHandlerFields();
            List<String> fieldList = Lists.newArrayList(needHandlerFields);
            if (fieldList.contains(name)) {
                handler.exportHandler(obj, name, value);
                break;
            }
        }
        return super.exportHandler(obj, name, value);
    }
}

